package org.dromara.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.open.bean.result.WxOpenResult;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.platform.domain.TMiniProgramBaseInfo;
import org.dromara.platform.mapper.TMiniProgramBaseInfoMapper;
import org.dromara.wechat.domain.MiniProgramDomainBo;
import org.dromara.wechat.enums.WechatEnums;
import org.dromara.wechat.service.WechatOpenService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.platform.domain.bo.TMiniProgramDomainBo;
import org.dromara.platform.domain.vo.TMiniProgramDomainVo;
import org.dromara.platform.domain.TMiniProgramDomain;
import org.dromara.platform.mapper.TMiniProgramDomainMapper;
import org.dromara.platform.service.ITMiniProgramDomainService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 小程序域名信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-06-06
 */
@RequiredArgsConstructor
@Service
public class TMiniProgramDomainServiceImpl implements ITMiniProgramDomainService {

    private final TMiniProgramDomainMapper baseMapper;
    private final WechatOpenService wechatOpenService;
    private final TMiniProgramBaseInfoMapper baseInfoMapper;
    /**
     * 查询小程序域名信息
     *
     * @param id 主键
     * @return 小程序域名信息
     */
    @Override
    public TMiniProgramDomainVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询小程序域名信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 小程序域名信息分页列表
     */
    @Override
    public TableDataInfo<TMiniProgramDomainVo> queryPageList(TMiniProgramDomainBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TMiniProgramDomain> lqw = buildQueryWrapper(bo);
        Page<TMiniProgramDomainVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的小程序域名信息列表
     *
     * @param bo 查询条件
     * @return 小程序域名信息列表
     */
    @Override
    public List<TMiniProgramDomainVo> queryList(TMiniProgramDomainBo bo) {
        LambdaQueryWrapper<TMiniProgramDomain> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TMiniProgramDomain> buildQueryWrapper(TMiniProgramDomainBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TMiniProgramDomain> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TMiniProgramDomain::getId);
        lqw.eq(bo.getBaseId() != null, TMiniProgramDomain::getBaseId, bo.getBaseId());
        lqw.eq(StringUtils.isNotBlank(bo.getWebViewDomain()), TMiniProgramDomain::getWebViewDomain, bo.getWebViewDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getRequestDomain()), TMiniProgramDomain::getRequestDomain, bo.getRequestDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getWsrequestDomain()), TMiniProgramDomain::getWsrequestDomain, bo.getWsrequestDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getUploadDomain()), TMiniProgramDomain::getUploadDomain, bo.getUploadDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getDownloadDomain()), TMiniProgramDomain::getDownloadDomain, bo.getDownloadDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getUdpDomain()), TMiniProgramDomain::getUdpDomain, bo.getUdpDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getTcpDomain()), TMiniProgramDomain::getTcpDomain, bo.getTcpDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidRequestDomain()), TMiniProgramDomain::getInvalidRequestDomain, bo.getInvalidRequestDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidWsrequestDomain()), TMiniProgramDomain::getInvalidWsrequestDomain, bo.getInvalidWsrequestDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidUploadDomain()), TMiniProgramDomain::getInvalidUploadDomain, bo.getInvalidUploadDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidDownloadDomain()), TMiniProgramDomain::getInvalidDownloadDomain, bo.getInvalidDownloadDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidUdpDomain()), TMiniProgramDomain::getInvalidUdpDomain, bo.getInvalidUdpDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getInvalidTcpDomain()), TMiniProgramDomain::getInvalidTcpDomain, bo.getInvalidTcpDomain());
        lqw.eq(StringUtils.isNotBlank(bo.getNoIcpDomain()), TMiniProgramDomain::getNoIcpDomain, bo.getNoIcpDomain());
        return lqw;
    }

    /**
     * 新增小程序域名信息
     *
     * @param bo 小程序域名信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TMiniProgramDomainBo bo) {
        TMiniProgramDomain add = MapstructUtils.convert(bo, TMiniProgramDomain.class);
        validEntityBeforeSave(add,bo.getDomainType());
        // 调用微信接口
        MiniProgramDomainBo miniProgramDomainBo = new MiniProgramDomainBo();
        BeanUtils.copyProperties(bo, miniProgramDomainBo);
        // 查询小程序信息
        TMiniProgramBaseInfo baseInfo = baseInfoMapper.selectById(bo.getBaseId());
        if(null == baseInfo){
            throw new ServiceException("小程序信息不存在");
        }
        miniProgramDomainBo.setAuthorizerAppid(baseInfo.getAppid());
        WxOpenResult result = wechatOpenService.setMiniprogramDomain(miniProgramDomainBo);
        if (null != result && !WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
            throw new ServiceException(result.getErrmsg());
        } else if (WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
            // 保存域名信息
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            return flag;
        }
        return false;

    }

    /**
     * 修改小程序域名信息
     *
     * @param bo 小程序域名信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TMiniProgramDomainBo bo) {
        TMiniProgramDomain update = MapstructUtils.convert(bo, TMiniProgramDomain.class);
        validEntityBeforeSave(update, bo.getDomainType());
        // 调用微信接口
        MiniProgramDomainBo miniProgramDomainBo = new MiniProgramDomainBo();
        BeanUtils.copyProperties(bo, miniProgramDomainBo);
        // 查询小程序信息
        TMiniProgramBaseInfo baseInfo = baseInfoMapper.selectById(bo.getBaseId());
        if(null == baseInfo){
            throw new ServiceException("小程序信息不存在");
        }
        miniProgramDomainBo.setAuthorizerAppid(baseInfo.getAppid());
        WxOpenResult result = wechatOpenService.setMiniprogramDomain(miniProgramDomainBo);
        if (null != result && !WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
            throw new ServiceException(result.getErrmsg());
        } else if (WechatEnums.SUCCESS.getCode().equals(result.getErrcode())) {
            // 保存域名信息
            return baseMapper.updateById(update) > 0;
        }
        return false;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TMiniProgramDomain entity, String domainType){
        //TODO 做一些数据校验,如唯一约束
        // 查询是否变更信息
        TMiniProgramDomain old = baseMapper.selectById(entity.getId());
        if (old != null) {
            // 服务器域名变更
            if("1".equals(domainType)){
                if(entity.getRequestDomain().equals(old.getRequestDomain()) && entity.getWsrequestDomain().equals(old.getWsrequestDomain()) && entity.getUploadDomain().equals(old.getUploadDomain()) && entity.getDownloadDomain().equals(old.getDownloadDomain()) && entity.getUdpDomain().equals(old.getUdpDomain()) && entity.getTcpDomain().equals(old.getTcpDomain()) ){
                    throw new ServiceException("服务器域名未变更");
                }
            }else if("2".equals(domainType)){
                if(entity.getWebViewDomain().equals(old.getWebViewDomain())){
                    throw new ServiceException("业务域名未变更");
                }
            }
        }
    }

    /**
     * 校验并批量删除小程序域名信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
